import {defineStore} from 'pinia';
import {readonly, ref} from 'vue';
//导入全局状态-总价
import { usePriceStore } from './price';

// 定义购物清单类型
export interface ShoppingList{
    [index:string]:{price:number,count:number}
};
// 定义全局状态-购物清单
export const useListStore=defineStore('list',()=>{
    //初始化购物清单细节
    const detail=ref<ShoppingList>({});
    //初始化购物清单长度
    const length=ref<number>(0);
    //使用全局状态-总价
    const totalPrice=usePriceStore();
    //更新购物清单方法
    function update(item:ShoppingList):void{
        //解析参数信息
        const name:string=Object.keys(item)[0];
        const price:number=item[name].price;
        const count:number=item[name].count;
        //更新购物清单中对应项
        if(name in detail.value){
            (detail.value)[name].count+=count;
        }else{
            Object.assign(detail.value,JSON.parse(JSON.stringify(item)));
            length.value++;
        }
        //更新全局状态-总价
        totalPrice.add(price*count);
        //移除数量为0的菜品项
        if((detail.value)[name].count === 0){
            delete (detail.value)[name];
            length.value--;
        }
    }
    //清空购物清单方法
    function clear():void{
        detail.value={};
        length.value=0;
        totalPrice.reset();
    }
    return {
        detail:readonly(detail),
        length:readonly(length),
        update,
        clear
    };
});
